import os
import logging
from typing import List, Dict, Any, Optional
from langchain.schema import Document

# 导入新的向量存储客户端
from app.utils.vectorstore_client import VectorStoreClient, Document, OnlineEmbeddings

# 为向后兼容而保留的类
class SiliconFlowEmbeddings(OnlineEmbeddings):
    """为了向后兼容而保留的类，转发到OnlineEmbeddings"""
    pass

class VectorStoreService:
    """向量存储服务，管理产品文档的向量存储（向后兼容版本）"""
    
    _instance = None
    
    @classmethod
    def get_instance(cls):
        """获取单例实例"""
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance
    
    def __init__(self):
        """初始化向量存储"""
        self.client = VectorStoreClient.get_instance()
        self._is_initialized = self.client.is_initialized
        self._initialization_error = VectorStoreClient.get_init_error()
        
    async def add_documents(self, documents: List[Document], product_id: str):
        """添加文档到向量存储"""
        try:
            if not self._is_initialized:
                return {"status": "error", "message": f"向量存储未初始化: {self._initialization_error}"}
            
            # 使用新客户端
            store_path = os.path.join("products", product_id)
            success, error_msg = await self.client.update_product_vectorstore(product_id, documents, store_path)
            
            if success:
                return {"status": "success", "message": f"成功添加 {len(documents)} 个文档"}
            else:
                return {"status": "error", "message": f"添加文档失败: {error_msg}"}
        except Exception as e:
            logging.error(f"添加文档到向量存储失败: {str(e)}")
            return {"status": "error", "message": f"添加文档失败: {str(e)}"}
    
    async def delete_by_product_id(self, product_id: str):
        """删除指定产品ID的所有文档"""
        try:
            if not self._is_initialized:
                return {"status": "error", "message": f"向量存储未初始化: {self._initialization_error}"}
            
            # 使用新客户端
            store_path = os.path.join("products", product_id)
            success = await self.client.delete_vectorstore(store_path)
            
            if success:
                return {"status": "success", "message": "成功删除产品文档"}
            else:
                return {"status": "error", "message": "删除产品文档失败"}
        except Exception as e:
            logging.error(f"删除产品文档失败: {str(e)}")
            return {"status": "error", "message": f"删除产品文档失败: {str(e)}"}
    
    async def update_product_documents(self, documents: List[Document], product_id: str):
        """更新产品的文档（先删除旧文档，再添加新文档）"""
        try:
            if not self._is_initialized:
                return {"status": "error", "message": f"向量存储未初始化: {self._initialization_error}"}
            
            # 使用新客户端
            store_path = os.path.join("products", product_id)
            success, error_msg = await self.client.update_product_vectorstore(product_id, documents, store_path)
            
            if success:
                return {"status": "success", "message": f"成功更新 {len(documents)} 个文档"}
            else:
                return {"status": "error", "message": f"更新文档失败: {error_msg}"}
        except Exception as e:
            logging.error(f"更新产品文档失败: {str(e)}")
            return {"status": "error", "message": f"更新产品文档失败: {str(e)}"}
    
    async def query_similar_documents(self, query: str, top_k: int = 5) -> List[Document]:
        """查询相似文档"""
        try:
            if not self._is_initialized:
                logging.error(f"向量存储未初始化: {self._initialization_error}")
                return []
            
            # 使用新客户端，搜索所有产品
            documents = await self.client.similarity_search(query, k=top_k)
            return documents
        except Exception as e:
            logging.error(f"查询相似文档失败: {str(e)}")
            return [] 